document.addEventListener('DOMContentLoaded', () => {
    // DOM元素
    const logContainer = document.getElementById('log-container');
    const levelFilter = document.getElementById('level-filter');
    const moduleFilter = document.getElementById('module-filter');
    const sessionFilter = document.getElementById('session-filter');
    const searchInput = document.getElementById('search-input');
    const clearLogsBtn = document.getElementById('clear-logs');
    const toggleAutoScrollBtn = document.getElementById('toggle-auto-scroll');
    const toggleDeduplicationBtn = document.getElementById('toggle-deduplication');
    const statusIndicator = document.getElementById('status-indicator');
    const statusText = document.getElementById('status-text');
    const logCount = document.getElementById('log-count');
    const sessionInfo = document.getElementById('session-info');
    const currentSessionId = document.getElementById('current-session-id');
    const activeDevicesCount = document.getElementById('active-devices-count');
    const sidebarToggle = document.getElementById('sidebar-toggle');
    const sidebar = document.querySelector('.sidebar');
    const deviceTotalSessions = document.getElementById('device-total-sessions');
    const deviceFirstConnected = document.getElementById('device-first-connected');

    // toggleHistoryBtn and historySessions elements removed
    // tabContainer element removed from HTML
    const controlsMoreToggle = document.getElementById('controls-more-toggle');
    const controlsSecondary = document.getElementById('controls-secondary');
    const copySessionBtn = document.getElementById('copy-session-id');
    const toast = document.getElementById('toast');
    
    // 状态指示器元素
    // logStatusIndicator element removed from HTML
    // statusIcon and statusTextSpan elements removed from HTML
    // statusDescription element removed from HTML
    const backToRealtimeBtn = document.getElementById('back-to-realtime');

    const collapseAllSessionsBtn = document.getElementById('collapse-all-sessions');
    // 日志级别过滤器使用下拉选择器而不是复选框
    


    // 缓存管理
    const CacheManager = {
        // 缓存键名常量
        KEYS: {
            USER_SETTINGS: 'log_monitor_user_settings',
            DEVICE_STATES: 'log_monitor_device_states',
            LOG_CACHE: 'log_monitor_log_cache',
            LAST_UPDATE: 'log_monitor_last_update'
        },
        
        // 获取缓存数据
        get(key, defaultValue = null) {
            try {
                const data = localStorage.getItem(key);
                return data ? JSON.parse(data) : defaultValue;
            } catch (error) {
                console.warn('获取缓存失败:', error);
                return defaultValue;
            }
        },
        
        // 设置缓存数据
        set(key, value) {
            try {
                localStorage.setItem(key, JSON.stringify(value));
                return true;
            } catch (error) {
                console.warn('设置缓存失败:', error);
                return false;
            }
        },
        
        // 删除缓存数据
        remove(key) {
            try {
                localStorage.removeItem(key);
                return true;
            } catch (error) {
                console.warn('删除缓存失败:', error);
                return false;
            }
        },
        
        // 清除所有缓存
        clear() {
            try {
                Object.values(this.KEYS).forEach(key => {
                    localStorage.removeItem(key);
                });
                return true;
            } catch (error) {
                console.warn('清除缓存失败:', error);
                return false;
            }
        },
        
        // 获取缓存大小
        getSize() {
            try {
                let size = 0;
                Object.values(this.KEYS).forEach(key => {
                    const data = localStorage.getItem(key);
                    if (data) {
                        size += data.length;
                    }
                });
                return size;
            } catch (error) {
                console.warn('获取缓存大小失败:', error);
                return 0;
            }
        }
    };
    
    // 用户设置管理
    const UserSettings = {
        // 默认设置
        defaults: {
            autoScroll: true,
            useDeduplication: true,
            selectedDevice: null,
            levelFilter: 'all',
            moduleFilter: 'all',
            sessionFilter: 'all',
            searchText: '',
            filtersExpanded: window.innerWidth >= 768,
            sidebarCollapsed: false,
            viewMode: 'table'
        },
        
        // 加载设置
        load() {
            const saved = CacheManager.get(CacheManager.KEYS.USER_SETTINGS, {});
            return { ...this.defaults, ...saved };
        },
        
        // 保存设置
        save(settings) {
            const current = this.load();
            const updated = { ...current, ...settings };
            return CacheManager.set(CacheManager.KEYS.USER_SETTINGS, updated);
        },
        
        // 获取单个设置
        get(key) {
            const settings = this.load();
            return settings[key];
        },
        
        // 设置单个值
        set(key, value) {
            const settings = this.load();
            settings[key] = value;
            return this.save(settings);
        },
        
        // 重置到默认值
        reset() {
            return CacheManager.set(CacheManager.KEYS.USER_SETTINGS, this.defaults);
        }
    };
    
    // 日志数据缓存管理
    const LogCache = {
        // 最大缓存数量（防止占用过多内存）
        MAX_CACHE_SIZE: 1000,
        
        // 缓存过期时间（毫秒）
        CACHE_EXPIRE_TIME: 30 * 60 * 1000, // 30分钟
        
        // 加载缓存的日志
        load() {
            const cached = CacheManager.get(CacheManager.KEYS.LOG_CACHE, {
                logs: [],
                timestamp: 0,
                modules: []
            });
            
            // 检查缓存是否过期
            if (Date.now() - cached.timestamp > this.CACHE_EXPIRE_TIME) {
                console.log('日志缓存已过期，清空缓存');
                return { logs: [], modules: [] };
            }
            
            return {
                logs: cached.logs || [],
                modules: cached.modules || []
            };
        },
        
        // 保存日志到缓存
        save(logs, modules) {
            // 限制缓存大小
            const logsToCache = logs.length > this.MAX_CACHE_SIZE 
                ? logs.slice(-this.MAX_CACHE_SIZE) 
                : logs;
            
            const cacheData = {
                logs: logsToCache,
                modules: Array.from(modules),
                timestamp: Date.now()
            };
            
            return CacheManager.set(CacheManager.KEYS.LOG_CACHE, cacheData);
        },
        
        // 清除日志缓存
        clear() {
            return CacheManager.remove(CacheManager.KEYS.LOG_CACHE);
        },
        
        // 添加新日志到缓存
        addLog(log) {
            const cached = this.load();
            cached.logs.push(log);
            
            // 更新模块列表
            if (log.module && !cached.modules.includes(log.module)) {
                cached.modules.push(log.module);
            }
            
            // 保存更新后的缓存
            this.save(cached.logs, new Set(cached.modules));
        },
        
        // 获取缓存统计信息
        getStats() {
            const cached = this.load();
            return {
                logCount: cached.logs.length,
                moduleCount: cached.modules.length,
                lastUpdate: CacheManager.get(CacheManager.KEYS.LOG_CACHE, {}).timestamp || 0
            };
        }
    };
    
    // 设备状态缓存管理
    const DeviceCache = {
        // 缓存过期时间（毫秒）
        CACHE_EXPIRE_TIME: 5 * 60 * 1000, // 5分钟
        
        // 加载设备状态缓存
        load() {
            const cached = CacheManager.get(CacheManager.KEYS.DEVICE_STATES, {
                devices: {},
                activeDevices: [],
                deviceSessions: {},
                timestamp: 0
            });
            
            // 检查缓存是否过期
            if (Date.now() - cached.timestamp > this.CACHE_EXPIRE_TIME) {
                console.log('设备状态缓存已过期，清空缓存');
                return {
                    devices: {},
                    activeDevices: [],
                    deviceSessions: {}
                };
            }
            
            return {
                devices: cached.devices || {},
                activeDevices: cached.activeDevices || [],
                deviceSessions: cached.deviceSessions || {}
            };
        },
        
        // 保存设备状态
        save(devices, activeDevices, deviceSessions) {
            const cacheData = {
                devices: Object.fromEntries(devices),
                activeDevices: Array.from(activeDevices),
                deviceSessions: Object.fromEntries(deviceSessions),
                timestamp: Date.now()
            };
            
            return CacheManager.set(CacheManager.KEYS.DEVICE_STATES, cacheData);
        },
        
        // 清除设备状态缓存
        clear() {
            return CacheManager.remove(CacheManager.KEYS.DEVICE_STATES);
        },
        
        // 获取缓存统计信息
        getStats() {
            const cached = this.load();
            return {
                deviceCount: Object.keys(cached.devices).length,
                activeDeviceCount: cached.activeDevices.length,
                sessionCount: Object.keys(cached.deviceSessions).length,
                lastUpdate: CacheManager.get(CacheManager.KEYS.DEVICE_STATES, {}).timestamp || 0
            };
        }
    };
    
    // 应用用户设置
    function applyUserSettings() {
        const settings = UserSettings.load();
        
        // 应用自动滚动设置
        autoScroll = settings.autoScroll;
        if (toggleAutoScrollBtn) {
            toggleAutoScrollBtn.classList.toggle('active', autoScroll);
            toggleAutoScrollBtn.title = autoScroll ? '关闭自动滚动' : '开启自动滚动';
        }
        
        // 应用去重设置
        useDeduplication = settings.useDeduplication;
        if (toggleDeduplicationBtn) {
            toggleDeduplicationBtn.classList.toggle('active', useDeduplication);
            toggleDeduplicationBtn.title = useDeduplication ? '关闭去重模式' : '开启去重模式';
        }
        
        // 应用过滤器设置
        if (levelFilter) levelFilter.value = settings.levelFilter;
        if (moduleFilter) moduleFilter.value = settings.moduleFilter;
        if (sessionFilter) sessionFilter.value = settings.sessionFilter;
        if (searchInput) searchInput.value = settings.searchText;
        
        // 应用过滤器展开状态
        const filterSecondary = document.getElementById('filter-secondary');
        const filtersToggle = document.getElementById('filters-toggle');
        if (filterSecondary && filtersToggle) {
            if (settings.filtersExpanded) {
                filterSecondary.classList.add('expanded');
                filtersToggle.classList.add('expanded');
                filtersToggle.title = '收起过滤器';
            } else {
                filterSecondary.classList.remove('expanded');
                filtersToggle.classList.remove('expanded');
                filtersToggle.title = '展开更多过滤器';
            }
        }
        
        // 应用侧边栏状态（仅在桌面端）
        if (window.innerWidth > 1024 && sidebar) {
            if (settings.sidebarCollapsed) {
                sidebar.classList.add('collapsed');
            } else {
                sidebar.classList.remove('collapsed');
            }
        }
        
        console.log('已加载用户设置:', settings);
    }
    
    // 保存当前设置
    function saveCurrentSettings() {
        const settings = {
            autoScroll: autoScroll,
            useDeduplication: useDeduplication,
            selectedDevice: selectedDevice,
            levelFilter: levelFilter ? levelFilter.value : 'all',
            moduleFilter: moduleFilter ? moduleFilter.value : 'all',
            sessionFilter: sessionFilter ? sessionFilter.value : 'all',
            searchText: searchInput ? searchInput.value : '',
            filtersExpanded: document.getElementById('filter-secondary')?.classList.contains('expanded') || false,
            sidebarCollapsed: sidebar?.classList.contains('collapsed') || false,
            viewMode: viewMode
        };
        
        UserSettings.save(settings);
    }

    // 初始化过滤器事件监听
    function initFilterEvents() {
        // 级别过滤器
        if (levelFilter) {
            levelFilter.addEventListener('change', () => {
                applyFilters();
                UserSettings.set('levelFilter', levelFilter.value);
            });
        }
        
        // 模块过滤器
        if (moduleFilter) {
            moduleFilter.addEventListener('change', () => {
                applyFilters();
                UserSettings.set('moduleFilter', moduleFilter.value);
            });
        }
        
        // 会话过滤器
        if (sessionFilter) {
            sessionFilter.addEventListener('change', () => {
                applyFilters();
                UserSettings.set('sessionFilter', sessionFilter.value);
            });
        }
        
        // 搜索输入
        if (searchInput) {
            searchInput.addEventListener('input', debounce(() => {
                applyFilters();
                UserSettings.set('searchText', searchInput.value);
            }, 300));
        }
        
        // 自动滚动切换
        if (toggleAutoScrollBtn) {
            toggleAutoScrollBtn.addEventListener('click', () => {
                autoScroll = !autoScroll;
                toggleAutoScrollBtn.classList.toggle('active', autoScroll);
                toggleAutoScrollBtn.title = autoScroll ? '关闭自动滚动' : '开启自动滚动';
                UserSettings.set('autoScroll', autoScroll);
            });
        }
        
        // 去重模式切换
        if (toggleDeduplicationBtn) {
            toggleDeduplicationBtn.addEventListener('click', () => {
                useDeduplication = !useDeduplication;
                toggleDeduplicationBtn.classList.toggle('active', useDeduplication);
                toggleDeduplicationBtn.title = useDeduplication ? '关闭去重模式' : '开启去重模式';
                UserSettings.set('useDeduplication', useDeduplication);
                // 重新加载日志数据
                applyFilters();
            });
        }
        
        // 清除日志
        if (clearLogsBtn) {
            clearLogsBtn.addEventListener('click', () => {
                if (confirm('确定要清除所有日志吗？')) {
                    logs = [];
                    modules.clear();
                    sessionLogs.clear();
                    sessionCollapseStates.clear();
                    logContainer.innerHTML = '';
                    logCount.textContent = '0';
                    updateModuleFilter();
                    
                    // 清除日志缓存
                    LogCache.clear();
                    console.log('已清除日志和缓存');
                }
            });
        }
    }

    // 初始化WebSocket连接
    function initWebSocket() {
        // 获取当前主机名和端口，用于WebSocket连接
        const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
        const host = window.location.hostname || 'localhost';
        const port = 3333; // 服务器WebSocket端口

        const wsUrl = `${protocol}//${host}:${port}`;
        
        statusIndicator.classList.remove('connected');
        statusIndicator.classList.add('connecting');
        statusText.textContent = '正在连接...';

        // 创建WebSocket连接
        socket = new WebSocket(wsUrl);

        // 连接建立时
        socket.onopen = () => {
            console.log('WebSocket连接已建立');
            statusIndicator.classList.remove('connecting');
            statusIndicator.classList.add('connected');
            statusText.textContent = '已连接';
            reconnectAttempts = 0;
            if (reconnectTimeout) {
                clearTimeout(reconnectTimeout);
                reconnectTimeout = null;
            }
        };

        // 接收消息
        socket.onmessage = (event) => {
            try {
                const data = JSON.parse(event.data);
                if (data.type === 'log') {
                    // 处理日志消息
                    const logData = data.data;
                    addLog(logData);
                    
                    // 更新会话日志计数
                    if (logData.sessionId) {
                        const count = sessionLogs.get(logData.sessionId) || 0;
                        sessionLogs.set(logData.sessionId, count + 1);
                    }
                    
                    // 标记设备有新日志
                    if (logData.deviceId) {
                        markDeviceHasNewLogs(logData.deviceId);
                    }
                    
                } else if (data.type === 'device_registered') {
                    // 处理设备注册确认
                    console.log('设备注册成功:', data);
                    // 重新加载设备列表和活跃设备
                    loadDevices();
                    loadActiveDevices();
                } else {
                    // 兼容旧格式
                    addLog(data);
                }
            } catch (error) {
                console.error('解析消息失败:', error);
            }
        };

        // 连接关闭
        socket.onclose = () => {
            console.log('WebSocket连接已关闭');
            statusIndicator.classList.remove('connected', 'connecting');
            statusText.textContent = '连接已断开';
            
            // 尝试重新连接
            if (reconnectAttempts < maxReconnectAttempts) {
                reconnectAttempts++;
                statusText.textContent = `连接已断开，${reconnectInterval/1000}秒后重试 (${reconnectAttempts}/${maxReconnectAttempts})`;
                reconnectTimeout = setTimeout(initWebSocket, reconnectInterval);
            } else {
                statusText.textContent = '连接失败，请刷新页面重试';
            }
        };

        // 连接错误
        socket.onerror = (error) => {
            console.error('WebSocket错误:', error);
        };
    }

    // 会话管理函数

    // 设备管理函数
    function loadDevices() {
        fetch('/api/devices')
            .then(response => response.json())
            .then(data => {
                devices.clear();
                data.forEach(device => {
                    devices.set(device.id, device);
                });
                updateDeviceList();
                
                // 保存到缓存
                DeviceCache.save(devices, activeDevices, deviceSessions);
                
                // 自动选择第一个活跃设备作为默认设备
                if (devices.size > 0 && !selectedDevice) {
                    const firstActiveDevice = Array.from(devices.keys()).find(deviceId => activeDevices.has(deviceId));
                    if (firstActiveDevice) {
                        switchDevice(firstActiveDevice);
                    } else {
                        // 如果没有活跃设备，选择第一个设备
                        const firstDevice = Array.from(devices.keys())[0];
                        if (firstDevice) {
                            switchDevice(firstDevice);
                        }
                    }
                }
            })
            .catch(error => console.error('加载设备列表失败:', error));
    }

    function loadActiveDevices() {
        fetch('/api/active-devices')
            .then(response => response.json())
            .then(data => {
                activeDevices.clear();
                data.forEach(deviceId => {
                    activeDevices.add(deviceId);
                });
                updateActiveDevicesCount();
                updateDeviceList();
                
                // 保存到缓存
                DeviceCache.save(devices, activeDevices, deviceSessions);
                
                // 如果还没有选择设备，自动选择第一个活跃设备
                if (!selectedDevice && devices.size > 0) {
                    const firstActiveDevice = Array.from(devices.keys()).find(deviceId => activeDevices.has(deviceId));
                    if (firstActiveDevice) {
                        switchDevice(firstActiveDevice);
                    } else {
                        // 如果没有活跃设备，选择第一个设备
                        const firstDevice = Array.from(devices.keys())[0];
                        if (firstDevice) {
                            switchDevice(firstDevice);
                        }
                    }
                }
            })
            .catch(error => console.error('加载活跃设备失败:', error));
    }

    function updateActiveDevicesCount() {
        if (activeDevicesCount) {
            activeDevicesCount.textContent = activeDevices.size;
        }
    }

    function updateDeviceList() {
        const deviceList = document.getElementById('device-list');
        if (!deviceList) return;

        deviceList.innerHTML = '';

        // 只显示具体的设备，不包括【全部设备】选项
        devices.forEach((device, deviceId) => {
            const deviceItem = document.createElement('div');
            deviceItem.className = 'device-item';
            deviceItem.setAttribute('data-device', deviceId);
            
            const isActive = activeDevices.has(deviceId);
            if (isActive) {
                deviceItem.classList.add('active');
            }
            
            deviceItem.innerHTML = `
                <span class="material-icons device-icon">computer</span>
                <span class="device-name">${device.name || deviceId}</span>
                <span class="material-icons device-status-icon ${isActive ? 'online' : 'offline'}">
                    circle
                </span>
            `;
            
            deviceItem.addEventListener('click', () => switchDevice(deviceId));
            deviceList.appendChild(deviceItem);
        });
    }

    // 在switchDevice中保存设备选择
    function switchDevice(deviceId) {
        // 设置当前选中的设备
        selectedDevice = deviceId;
        UserSettings.set('selectedDevice', deviceId);
        
        // 切换到指定设备
        document.querySelectorAll('.device-item').forEach(item => {
            item.classList.remove('selected');
        });
        
        const selectedItem = document.querySelector(`[data-device="${deviceId}"]`);
        if (selectedItem) {
            selectedItem.classList.add('selected');
        }
        
        // 重置会话过滤器为默认状态
        sessionFilter.value = 'all';
        UserSettings.set('sessionFilter', 'all');
        
        // 加载设备统计信息
        loadDeviceStats(deviceId);
        loadDeviceSessions(deviceId);
        
        // 应用过滤器
        applyFilters();
    }

    function loadDeviceStats(deviceId) {
        if (!deviceId) {
            console.warn('设备ID为空，跳过加载设备统计');
            return;
        }
        
        fetch(`/api/device-stats/${deviceId}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                return response.json();
            })
            .then(response => {
                const data = response.data;
                if (deviceTotalSessions) {
                    deviceTotalSessions.textContent = data.total_sessions || 0;
                }
                if (deviceFirstConnected) {
                    deviceFirstConnected.textContent = data.first_connected ? 
                        new Date(data.first_connected).toLocaleString() : '-';
                }
                
                // 更新当前会话ID显示
                if (currentSessionId && data.current_session_id) {
                    currentSessionId.textContent = data.current_session_id;
                } else if (currentSessionId) {
                    currentSessionId.textContent = '-';
                }
            })
            .catch(error => console.error('加载设备统计失败:', error));
    }

    function loadDeviceSessions(deviceId) {
        if (!deviceId) {
            console.warn('设备ID为空，跳过加载设备会话');
            return;
        }
        
        fetch(`/api/devices/${deviceId}/sessions`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                return response.json();
            })
            .then(data => {
                deviceSessions.set(deviceId, data);
                updateSessionInfo(deviceId);
                // 更新会话过滤器，只显示当前设备的会话
                updateSessionFilter(data);
                
                // 保存到缓存
                DeviceCache.save(devices, activeDevices, deviceSessions);
            })
            .catch(error => console.error('加载设备会话失败:', error));
    }

    function updateSessionInfo(deviceId) {
        const sessions = deviceSessions.get(deviceId) || [];
        const activeSession = sessions.find(s => s.is_active);
        
        if (currentSessionId) {
            if (activeSession) {
                currentSessionId.textContent = activeSession.id;
            } else {
                currentSessionId.textContent = '-';
            }
        }
    }

    function markDeviceHasNewLogs(deviceId) {
        const deviceItem = document.querySelector(`[data-device="${deviceId}"]`);
        if (deviceItem) {
            deviceItem.classList.add('has-new-logs');
        }
    }



    // 控件 '更多' 切换逻辑
    function initFiltersToggle() {
        const filtersToggle = document.getElementById('filters-toggle');
        const filterSecondary = document.getElementById('filter-secondary');
        
        if (!filtersToggle || !filterSecondary) return;
        
        // 初始在窄屏隐藏次要控件
        filtersToggle.addEventListener('click', () => {
            const expanded = filterSecondary.classList.contains('expanded');
            
            if (expanded) {
                filterSecondary.classList.remove('expanded');
                filtersToggle.classList.remove('expanded');
                filtersToggle.title = '展开更多过滤器';
                UserSettings.set('filtersExpanded', false);
            } else {
                filterSecondary.classList.add('expanded');
                filtersToggle.classList.add('expanded');
                filtersToggle.title = '收起过滤器';
                UserSettings.set('filtersExpanded', true);
            }
        });
        
        // 在桌面端默认展开
        if (window.innerWidth >= 768) {
            filterSecondary.classList.add('expanded');
            filtersToggle.classList.add('expanded');
            filtersToggle.title = '收起过滤器';
        }
        
        // 监听窗口大小变化
        window.addEventListener('resize', () => {
            if (window.innerWidth >= 768 && !filterSecondary.classList.contains('expanded')) {
                filterSecondary.classList.add('expanded');
                filtersToggle.classList.add('expanded');
                filtersToggle.title = '收起过滤器';
                UserSettings.set('filtersExpanded', true);
            }
        });
    }

    initFiltersToggle();

    // 侧边栏折叠逻辑
    function initSidebarToggle() {
        if (!sidebarToggle || !sidebar) return;
        
        const sidebarOverlay = document.getElementById('sidebar-overlay');
        
        sidebarToggle.addEventListener('click', () => {
            const isExpanded = sidebar.classList.contains('expanded');
            
            if (window.innerWidth <= 1024) {
                // 移动端：切换侧边栏和覆盖层
                if (isExpanded) {
                    sidebar.classList.remove('expanded');
                    if (sidebarOverlay) {
                        sidebarOverlay.classList.remove('active');
                    }
                } else {
                    sidebar.classList.add('expanded');
                    if (sidebarOverlay) {
                        sidebarOverlay.classList.add('active');
                    }
                }
            } else {
                // 桌面端：切换折叠状态
                const willCollapse = !sidebar.classList.contains('collapsed');
                sidebar.classList.toggle('collapsed');
                UserSettings.set('sidebarCollapsed', willCollapse);
            }
        });
        
        // 点击覆盖层关闭侧边栏
        if (sidebarOverlay) {
            sidebarOverlay.addEventListener('click', () => {
                sidebar.classList.remove('expanded');
                sidebarOverlay.classList.remove('active');
            });
        }
        
        // 监听窗口大小变化
        window.addEventListener('resize', () => {
            if (window.innerWidth > 1024) {
                // 桌面端：移除移动端样式
                sidebar.classList.remove('expanded');
                if (sidebarOverlay) {
                    sidebarOverlay.classList.remove('active');
                }
            } else {
                // 移动端：移除桌面端样式
                sidebar.classList.remove('collapsed');
            }
        });
    }

    initSidebarToggle();

    // 复制会话ID并显示提示
    function showToast(message, timeout = 1800) {
        if (!toast) return;
        toast.textContent = message;
        toast.classList.add('show');
        clearTimeout(toast._hideTimer);
        toast._hideTimer = setTimeout(() => {
            toast.classList.remove('show');
        }, timeout);
    }

    function initCopySessionId() {
        if (!copySessionBtn) return;
        copySessionBtn.addEventListener('click', async () => {
            const sessionIdEl = document.getElementById('current-session-id');
            if (!sessionIdEl) return;
            const text = sessionIdEl.textContent || '';
            try {
                if (navigator.clipboard && navigator.clipboard.writeText) {
                    await navigator.clipboard.writeText(text);
                } else {
                    // 后备方法
                    const ta = document.createElement('textarea');
                    ta.value = text;
                    document.body.appendChild(ta);
                    ta.select();
                    document.execCommand('copy');
                    ta.remove();
                }
                showToast('会话ID 已复制');
            } catch (err) {
                console.error('复制失败', err);
                showToast('复制失败');
            }
        });
    }

    initCopySessionId();
    

    
    // updateHistorySessions function removed - no longer needed
    
    function updateSessionFilter(sessions) {
        // 保存当前选择
        const currentSelection = sessionFilter.value;
        
        // 清除现有选项
        sessionFilter.innerHTML = '';
        
        // 添加默认选项
        const allOption = document.createElement('option');
        allOption.value = 'all';
        allOption.textContent = '所有会话';
        sessionFilter.appendChild(allOption);
        
        const currentOption = document.createElement('option');
        currentOption.value = 'current';
        currentOption.textContent = '当前会话';
        sessionFilter.appendChild(currentOption);
        
        // 如果没有选中设备，不显示具体会话选项
        if (!selectedDevice || !sessions || sessions.length === 0) {
            return;
        }
        
        // 按时间排序会话（最新的在前）
        const sortedSessions = sessions.sort((a, b) => {
            return new Date(b.start_time) - new Date(a.start_time);
        });
        
        // 添加会话选项，区分活跃和历史会话
        const activeSessions = sortedSessions.filter(session => !session.end_time);
        const historicalSessions = sortedSessions.filter(session => session.end_time);
        
        // 添加活跃会话
        if (activeSessions.length > 0) {
            const activeGroup = document.createElement('optgroup');
            activeGroup.label = '活跃会话';
            activeSessions.forEach(session => {
                const option = document.createElement('option');
                option.value = session.id;
                const sessionLabel = session.id ? session.id.substring(0, 8) : '未知';
                const logCount = session.log_count || 0;
                const startTime = new Date(session.start_time).toLocaleTimeString();
                option.textContent = `${sessionLabel} (${logCount}条) - ${startTime}`;
                option.className = 'active-session';
                activeGroup.appendChild(option);
            });
            sessionFilter.appendChild(activeGroup);
        }
        
        // 添加历史会话
        if (historicalSessions.length > 0) {
            const historyGroup = document.createElement('optgroup');
            historyGroup.label = '历史会话';
            historicalSessions.forEach(session => {
                const option = document.createElement('option');
                option.value = session.id;
                const sessionLabel = session.id ? session.id.substring(0, 8) : '未知';
                const logCount = session.log_count || 0;
                const startTime = new Date(session.start_time).toLocaleTimeString();
                const endTime = new Date(session.end_time).toLocaleTimeString();
                option.textContent = `${sessionLabel} (${logCount}条) - ${startTime}~${endTime}`;
                option.className = 'historical-session';
                historyGroup.appendChild(option);
            });
            sessionFilter.appendChild(historyGroup);
        }
        
        // 恢复之前的选择（如果仍然有效）
        if (currentSelection && [...sessionFilter.options].some(opt => opt.value === currentSelection)) {
            sessionFilter.value = currentSelection;
        }
    }
    
    // updateSessionLogCount function removed - no longer needed
    


    // 添加日志
    function addLog(logData) {
        // 如果正在显示历史日志，自动切换回实时模式
        if (showingHistory) {
            showingHistory = false;
        }
        
        // 添加时间戳（如果没有）
        if (!logData.timestamp) {
            logData.timestamp = new Date().toISOString();
        }
        
        // 标记为新日志
        logData.isNew = true;

        // 添加到日志数组
        logs.push(logData);
        
        // 更新模块列表
        if (logData.module && !modules.has(logData.module)) {
            modules.add(logData.module);
            updateModuleFilter();
        }
        
        // 添加到缓存
        LogCache.addLog(logData);

        // 应用过滤器并更新显示
        applyFilters();
        
        // 更新日志计数
        logCount.textContent = logs.length;
        
        // 3秒后移除新日志标记
        setTimeout(() => {
            logData.isNew = false;
            // 重新渲染以移除高亮
            applyFilters();
        }, 3333);
    }

    // 更新模块过滤器
    function updateModuleFilter() {
        // 保存当前选择
        const currentSelection = moduleFilter.value;
        
        // 清空现有选项（保留"全部"选项）
        while (moduleFilter.options.length > 1) {
            moduleFilter.remove(1);
        }
        
        // 添加模块选项
        modules.forEach(module => {
            const option = document.createElement('option');
            option.value = module;
            option.textContent = module;
            moduleFilter.appendChild(option);
        });
        
        // 恢复选择（如果可能）
        if (currentSelection && [...modules].includes(currentSelection)) {
            moduleFilter.value = currentSelection;
        }
    }

    // 应用过滤器
    function applyFilters() {
        // 如果正在显示历史会话日志，不应用过滤器
        if (showingHistory) {
            return;
        }
        
        // 保存当前会话的折叠状态
        saveSessionCollapseStates();
        
        // 获取选中的日志级别
        const selectedLevel = levelFilter.value;
        const selectedLevels = selectedLevel === 'all' ? ['info', 'warning', 'error', 'exception', 'emergency'] : [selectedLevel];
        
        const module = moduleFilter.value;
        const searchText = searchInput.value.toLowerCase();
        
        // 清空日志容器
        logContainer.innerHTML = '';
        
        // 过滤日志
        const filteredLogs = logs.filter(log => {
            // 级别过滤（多选）
            if (!selectedLevels.includes(log.level)) return false;
            
            // 模块过滤
            if (module !== 'all' && log.module !== module) return false;
            
            // 设备过滤
            if (selectedDevice && log.deviceId !== selectedDevice) return false;
            
            // 会话过滤
        if (true) {
                const sessionFilterValue = sessionFilter.value;
                if (sessionFilterValue === 'current' && log.sessionId !== currentSession) return false;
                if (sessionFilterValue !== 'all' && sessionFilterValue !== 'current' && log.sessionId !== sessionFilterValue) return false;
            }
            
            // 搜索过滤
            if (searchText && !log.message.toLowerCase().includes(searchText)) return false;
            
            return true;
        });
        
        // 按时间戳排序日志，确保连续重复的日志能被正确分组
        filteredLogs.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
        
        // 使用表格视图渲染所有日志
        renderTableView(filteredLogs);
        
        // 自动滚动到底部
        if (autoScroll) {
            logContainer.scrollTop = logContainer.scrollHeight;
        }
    }

    // 保存会话的折叠状态
    function saveSessionCollapseStates() {
        const sessionContainers = logContainer.querySelectorAll('.session-container');
        sessionContainers.forEach(container => {
            const sessionId = container.getAttribute('data-session-id');
            const sessionLogs = container.querySelector('.session-logs');
            if (sessionId && sessionLogs) {
                const isCollapsed = sessionLogs.style.display === 'none';
                sessionCollapseStates.set(sessionId, isCollapsed);
            }
        });
    }
    
    // 恢复会话的折叠状态
    function restoreSessionCollapseStates() {
        const sessionContainers = logContainer.querySelectorAll('.session-container');
        sessionContainers.forEach(container => {
            const sessionId = container.getAttribute('data-session-id');
            const sessionLogs = container.querySelector('.session-logs');
            const sessionToggle = container.querySelector('.session-toggle');
            
            if (sessionId && sessionLogs && sessionToggle) {
                const isCollapsed = sessionCollapseStates.get(sessionId);
                if (isCollapsed === true) {
                    sessionLogs.style.display = 'none';
                    sessionToggle.textContent = '▶';
                } else if (isCollapsed === false) {
                    sessionLogs.style.display = 'block';
                    sessionToggle.textContent = '▼';
                }
                // 如果没有保存的状态，保持默认展开状态
            }
        });
    }

    // 检查两条日志是否相同（除了时间戳）
    function areLogsEqual(log1, log2) {
        return log1.level === log2.level && 
               log1.module === log2.module && 
               log1.message === log2.message;
    }

    // 渲染会话组
    function renderSessionGroup(sessionId, sessionLogs) {
        // 创建会话容器
        const sessionContainer = document.createElement('div');
        sessionContainer.className = 'session-container';
        sessionContainer.setAttribute('data-session-id', sessionId);
        
        // 创建会话头部
        const sessionHeader = document.createElement('div');
        sessionHeader.className = 'session-header';
        
        const firstLog = sessionLogs[0];
        const lastLog = sessionLogs[sessionLogs.length - 1];
        const startTime = new Date(firstLog.timestamp).toLocaleString();
        const endTime = sessionLogs.length > 1 ? new Date(lastLog.timestamp).toLocaleString() : '';
        const deviceId = firstLog.deviceId || 'unknown';
        
        sessionHeader.innerHTML = `
            <div class="session-title">
                <span class="session-toggle" onclick="toggleSession(this)">▼</span>
                <span class="session-label">会话 ${sessionId}</span>
                <span class="session-device">[设备: ${deviceId}]</span>
                <span class="session-count">(${sessionLogs.length} 条日志)</span>
            </div>
            <div class="session-time">
                <span class="session-start">开始: ${startTime}</span>
                ${endTime ? `<span class="session-end">结束: ${endTime}</span>` : '<span class="session-status">进行中</span>'}
            </div>
        `;
        
        // 创建会话日志容器
        const sessionLogsContainer = document.createElement('div');
        sessionLogsContainer.className = 'session-logs';
        
        // 处理会话内的日志折叠（查找重复消息）
        const processedLogs = [];
        let currentGroup = null;
        
        sessionLogs.forEach((log, index) => {
            // 检查是否与前一条日志相同（除了时间戳）
            if (currentGroup && areLogsEqual(log, currentGroup.logs[0])) {
                // 添加到当前组
                currentGroup.logs.push(log);
                currentGroup.count++;
            } else {
                // 创建新组
                if (currentGroup) {
                    processedLogs.push(currentGroup);
                }
                currentGroup = {
                    logs: [log],
                    count: 1,
                    collapsed: true
                };
            }
            
            // 处理最后一组
            if (index === sessionLogs.length - 1 && currentGroup) {
                processedLogs.push(currentGroup);
            }
        });
        
        // 渲染日志组
        processedLogs.forEach(group => {
            const logEntry = renderLogGroup(group);
            sessionLogsContainer.appendChild(logEntry);
        });
        
        // 组装会话容器
        sessionContainer.appendChild(sessionHeader);
        sessionContainer.appendChild(sessionLogsContainer);
        
        logContainer.appendChild(sessionContainer);
    }
    
    // 渲染日志组
    function renderLogGroup(group) {
        const log = group.logs[0];
        const logEntry = document.createElement('div');
        let className = `log-entry ${log.level}`;
        
        // 如果是新日志，添加高亮样式
        if (log.isNew) {
            className += ' new-log';
        }
        
        logEntry.className = className;
        
        // 日志头部（时间戳、级别、模块）
        const logHeader = document.createElement('div');
        logHeader.className = 'log-header';
        
        // 左侧：折叠指示器、级别、模块
        const leftHeader = document.createElement('div');
        
        // 折叠指示器（仅当有多条日志时显示）
        if (group.count > 1) {
            const collapseIndicator = document.createElement('span');
            collapseIndicator.className = 'collapse-indicator';
            collapseIndicator.textContent = group.collapsed ? '▶' : '▼';
            collapseIndicator.addEventListener('click', () => toggleCollapse(group, logEntry));
            leftHeader.appendChild(collapseIndicator);
        }
        
        // 日志级别
        const logLevel = document.createElement('span');
        logLevel.className = `log-level ${log.level}`;
        logLevel.textContent = getLevelText(log.level);
        leftHeader.appendChild(logLevel);
        
        // 模块
        if (log.module) {
            const logModule = document.createElement('span');
            logModule.className = 'log-module';
            logModule.textContent = log.module;
            leftHeader.appendChild(logModule);
        }
        
        // 重复计数（如果有多条）
        if (group.count > 1) {
            const collapsedCount = document.createElement('span');
            collapsedCount.className = 'collapsed-count';
            collapsedCount.textContent = `x${group.count}`;
            leftHeader.appendChild(collapsedCount);
        }
        
        logHeader.appendChild(leftHeader);
        
        // 右侧：时间戳
        const logTimestamp = document.createElement('span');
        logTimestamp.className = 'log-timestamp';
        logTimestamp.textContent = formatTimestamp(log.timestamp);
        logHeader.appendChild(logTimestamp);
        
        logEntry.appendChild(logHeader);
        
        // 日志内容
        const logContent = document.createElement('div');
        logContent.className = 'log-content';
        logContent.textContent = log.message;
        logEntry.appendChild(logContent);
        
        // 折叠状态下仍然显示第一条日志的内容，让用户知道重复的内容是什么
        // 不再隐藏内容，让用户能看到重复日志的具体内容
        
        // 如果有多条日志且未折叠，显示所有日志
        if (group.count > 1 && !group.collapsed) {
            // 显示第一条之后的所有日志
            for (let i = 1; i < group.logs.length; i++) {
                const additionalLog = group.logs[i];
                const additionalEntry = document.createElement('div');
                additionalEntry.className = `log-entry ${additionalLog.level} additional-log`;
                
                // 仅显示时间戳和内容
                const additionalHeader = document.createElement('div');
                additionalHeader.className = 'log-header';
                
                const additionalTimestamp = document.createElement('span');
                additionalTimestamp.className = 'log-timestamp';
                additionalTimestamp.textContent = formatTimestamp(additionalLog.timestamp);
                additionalHeader.appendChild(additionalTimestamp);
                
                additionalEntry.appendChild(additionalHeader);
                
                const additionalContent = document.createElement('div');
                additionalContent.className = 'log-content';
                additionalContent.textContent = additionalLog.message;
                additionalEntry.appendChild(additionalContent);
                
                additionalEntry.dataset.groupId = logEntry.dataset.groupId;
                logEntry.appendChild(additionalEntry);
            }
        }
        
        return logEntry;
    }

    // 切换折叠状态
    function toggleCollapse(group, logEntry) {
        group.collapsed = !group.collapsed;
        
        // 更新折叠指示器
        const collapseIndicator = logEntry.querySelector('.collapse-indicator');
        if (collapseIndicator) {
            collapseIndicator.textContent = group.collapsed ? '▶' : '▼';
        }
        
        // 重新应用过滤器以更新显示
        applyFilters();
    }
    
    // 切换会话展开/折叠状态
    window.toggleSession = function(element) {
        const sessionContainer = element.closest('.session-container');
        const sessionLogs = sessionContainer.querySelector('.session-logs');
        const sessionId = sessionContainer.getAttribute('data-session-id');
        
        if (sessionLogs.style.display === 'none') {
            sessionLogs.style.display = 'block';
            element.textContent = '▼';
            // 更新状态记录
            if (sessionId) {
                sessionCollapseStates.set(sessionId, false);
            }
        } else {
            sessionLogs.style.display = 'none';
            element.textContent = '▶';
            // 更新状态记录
            if (sessionId) {
                sessionCollapseStates.set(sessionId, true);
            }
        }
    };

    // 格式化时间戳
    function formatTimestamp(timestamp) {
        const date = new Date(timestamp);
        return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false });
    }

    // 获取日志级别文本
    function getLevelText(level) {
        const levelTexts = {
            'debug': '调试',
            'info': '信息',
            'warning': '警告',
            'error': '错误',
            'exception': '异常',
            'emergency': '紧急'
        };
        return levelTexts[level] || level;
    }
    
    // 对连续重复的日志进行分组
    function groupConsecutiveLogs(logs) {
        if (logs.length === 0) return [];
        
        const groups = [];
        let currentGroup = {
            logs: [logs[0]],
            count: 1,
            collapsed: true,
            firstTimestamp: logs[0].timestamp,
            lastTimestamp: logs[0].timestamp
        };
        
        for (let i = 1; i < logs.length; i++) {
            const currentLog = logs[i];
            const lastLog = currentGroup.logs[currentGroup.logs.length - 1];
            
            // 检查是否为连续重复的日志（级别、模块、消息都相同）
            if (currentLog.level === lastLog.level && 
                currentLog.module === lastLog.module && 
                currentLog.message === lastLog.message) {
                // 添加到当前组
                currentGroup.logs.push(currentLog);
                currentGroup.count++;
                currentGroup.lastTimestamp = currentLog.timestamp;
            } else {
                // 开始新组
                groups.push(currentGroup);
                currentGroup = {
                    logs: [currentLog],
                    count: 1,
                    collapsed: true,
                    firstTimestamp: currentLog.timestamp,
                    lastTimestamp: currentLog.timestamp
                };
            }
        }
        
        // 添加最后一组
        groups.push(currentGroup);
        
        return groups;
    }
    
    // 表格视图渲染
    function renderTableView(filteredLogs) {
        logContainer.innerHTML = '';
        
        if (filteredLogs.length === 0) {
            logContainer.innerHTML = '<div class="no-logs">暂无日志数据</div>';
            return;
        }
        
        // 检查是否为去重日志（有count字段）
        const isDeduplicatedLogs = filteredLogs.length > 0 && filteredLogs[0].count !== undefined;
        
        if (isDeduplicatedLogs) {
            // 去重日志直接显示，不需要分组
            logGroups = filteredLogs.map(log => ({
                logs: [log],
                count: log.count || 1,
                collapsed: log.count > 1, // 默认折叠重复日志
                firstTimestamp: log.first_timestamp || log.timestamp,
                lastTimestamp: log.last_timestamp || log.timestamp
            }));
        } else {
            // 对实时日志进行分组并保存到全局变量
            logGroups = groupConsecutiveLogs(filteredLogs);
        }
        
        // 创建表格容器
        const tableContainer = document.createElement('div');
        tableContainer.className = 'table-container';
        
        // 创建表格
        const table = document.createElement('table');
        table.className = 'table-view';
        
        // 创建表头
        const thead = document.createElement('thead');
        thead.innerHTML = `
            <tr>
                <th>时间</th>
                <th>级别</th>
                <th>模块</th>
                <th>消息</th>
            </tr>
        `;
        table.appendChild(thead);
        
        // 创建表体
        const tbody = document.createElement('tbody');
        
        logGroups.forEach((group, groupIndex) => {
            const firstLog = group.logs[0];
            const row = document.createElement('tr');
            row.className = `log-row ${firstLog.level}`;
            row.setAttribute('data-group-index', groupIndex);
            
            if (firstLog.isNew) {
                row.classList.add('new-log');
            }
            
            // 时间戳显示
            let timestampDisplay;
            if (group.count > 1) {
                timestampDisplay = `${formatTimestamp(group.firstTimestamp)} ~ ${formatTimestamp(group.lastTimestamp)}`;
            } else {
                // 对于去重日志，使用first_timestamp或timestamp
                timestampDisplay = formatTimestamp(firstLog.first_timestamp || firstLog.timestamp);
            }
            
            // 消息显示
            let messageDisplay = firstLog.message;
            if (group.count > 1) {
                messageDisplay += ` <span class="repeat-count">x${group.count}</span>`;
            }
            
            // 添加折叠指示器
            let collapseIndicator = '';
            if (group.count > 1) {
                collapseIndicator = `<span class="collapse-toggle" onclick="toggleLogGroup(${groupIndex})">${group.collapsed ? '▶' : '▼'}</span> `;
            }
            
            row.innerHTML = `
                <td class="timestamp-col">${timestampDisplay}</td>
                <td class="level-col"><span class="log-level ${firstLog.level}">${getLevelText(firstLog.level)}</span></td>
                <td class="module-col">${firstLog.module || '-'}</td>
                <td class="message-col">${collapseIndicator}${messageDisplay}</td>
            `;
            
            tbody.appendChild(row);
            
            // 如果组有多条日志且未折叠，显示详细日志
            if (group.count > 1 && !group.collapsed) {
                group.logs.forEach((log, logIndex) => {
                    if (logIndex === 0) return; // 跳过第一条，已经显示了
                    
                    const detailRow = document.createElement('tr');
                    detailRow.className = `log-detail-row ${log.level}`;
                    detailRow.setAttribute('data-group-index', groupIndex);
                    
                    detailRow.innerHTML = `
                        <td class="timestamp-col detail-timestamp">${formatTimestamp(log.timestamp)}</td>
                        <td class="level-col"><span class="log-level ${log.level}">${getLevelText(log.level)}</span></td>
                        <td class="module-col">${log.module || '-'}</td>
                        <td class="message-col detail-message">${log.message}</td>
                    `;
                    
                    tbody.appendChild(detailRow);
                });
            }
        });
        
        table.appendChild(tbody);
        tableContainer.appendChild(table);
        logContainer.appendChild(tableContainer);
        
        // 自动滚动到底部
        if (autoScroll) {
            logContainer.scrollTop = logContainer.scrollHeight;
        }
    }

    // 全局变量存储日志组状态
    let logGroups = [];
    
    // 切换日志组的折叠状态
    window.toggleLogGroup = function(groupIndex) {
        if (logGroups[groupIndex]) {
            logGroups[groupIndex].collapsed = !logGroups[groupIndex].collapsed;
            
            // 重新渲染表格
            const currentLogs = getCurrentFilteredLogs();
            renderTableView(currentLogs);
        }
    };
    
    // 获取当前过滤后的日志
    function getCurrentFilteredLogs() {
        const searchText = searchInput.value.toLowerCase();
        const selectedLevel = levelFilter.value;
        const selectedModule = moduleFilter.value;
        const selectedSession = sessionFilter.value;
        
        return logs.filter(log => {
            // 级别过滤
            if (selectedLevel !== 'all' && log.level !== selectedLevel) return false;
            
            // 模块过滤
            if (selectedModule !== 'all' && log.module !== selectedModule) return false;
            
            // 会话过滤
            if (selectedSession === 'current' && (!currentSession || log.sessionId !== currentSession.id)) return false;
            if (selectedSession !== 'all' && selectedSession !== 'current' && log.sessionId !== selectedSession) return false;
            
            // 设备过滤
            if (selectedDevice && log.deviceId !== selectedDevice) return false;
            
            // 搜索过滤
            if (searchText && !log.message.toLowerCase().includes(searchText)) return false;
            
            return true;
        });
    }

    // 事件监听器
    levelFilter.addEventListener('change', applyFilters);
    moduleFilter.addEventListener('change', applyFilters);
    sessionFilter.addEventListener('change', onSessionFilterChange);
    searchInput.addEventListener('input', applyFilters);
    
    // 会话过滤器变化处理
    function onSessionFilterChange() {
        const selectedValue = sessionFilter.value;
        
        // 如果选择了特定会话（不是'all'或'current'），加载该会话的日志
        if (selectedValue !== 'all' && selectedValue !== 'current') {
            loadSessionLogs(selectedValue);
            return;
        }
        
        // 如果选择了'all'或'current'，退出历史模式并应用过滤器
        if (showingHistory) {
            showingHistory = false;
            const paginationControls = document.querySelector('.pagination-controls');
            if (paginationControls) {
                paginationControls.style.display = 'block';
            }
        }
        
        // 清除会话高亮
        document.querySelectorAll('.session-container').forEach(container => {
            container.classList.remove('highlighted-session');
        });
        
        // 应用过滤器
        applyFilters();
    }
    

    
    // 历史会话切换按钮 - removed
    
    // 去重模式按钮
    toggleDeduplicationBtn.addEventListener('click', toggleDeduplication);
    
    // 返回实时日志按钮
    backToRealtimeBtn.addEventListener('click', () => {
        window.backToRealtime();
    });
    
    // 折叠所有会话按钮
    collapseAllSessionsBtn.addEventListener('click', () => {
        collapseAllSessions();
    });
    

    
    // 日志级别过滤下拉选择器
    levelFilter.addEventListener('change', () => {
        // 重新应用所有过滤器，包括新的级别过滤
        applyFilters();
    });
    
    clearLogsBtn.addEventListener('click', async () => {
        const confirmMessage = '确定要清除所有日志吗？这将删除数据库中的所有日志记录。';
        
        if (confirm(confirmMessage)) {
            try {
                const response = await fetch('http://localhost:3333/api/logs', {
                    method: 'DELETE'
                });
                
                if (response.ok) {
                    logs = [];
                    logCount.textContent = '0';
                    
                    // 清空日志容器显示
                    const logContainer = document.getElementById('log-container');
                    if (logContainer) {
                        logContainer.innerHTML = '';
                    }
                    
                    // 清空相关数据
                    sessionLogs.clear();
                    
                    // 重置会话过滤器
                    sessionFilter.innerHTML = '<option value="all">全部会话</option><option value="current">当前会话</option>';
                    
                    // 重新加载统计信息
                    loadLogStats();
                    loadActiveDevices();
                    
                    alert('日志已清除');
                } else {
                    alert('清除日志失败');
                }
            } catch (error) {
                console.error('清除日志失败:', error);
                alert('清除日志失败');
            }
        }
    });
    
    toggleAutoScrollBtn.addEventListener('click', () => {
        autoScroll = !autoScroll;
        toggleAutoScrollBtn.textContent = autoScroll ? '自动滚动: 开启' : '自动滚动: 关闭';
        
        // 更新按钮样式
        if (autoScroll) {
            toggleAutoScrollBtn.classList.remove('btn-inactive');
            toggleAutoScrollBtn.classList.add('btn-active');
        } else {
            toggleAutoScrollBtn.classList.remove('btn-active');
            toggleAutoScrollBtn.classList.add('btn-inactive');
        }
    });
    
    // 历史日志按钮已在HTML中定义
    // 去重模式按钮已在HTML中定义
    
    // 设置分页控件事件
    setupPaginationEvents();

    // 加载所有会话
    async function loadAllSessions() {
        try {
            const response = await fetch('/api/sessions');
            if (response.ok) {
                const sessions = await response.json();
                updateSessionFilter(sessions);
            } else {
                console.error('加载会话列表失败:', response.statusText);
            }
        } catch (error) {
            console.error('加载会话列表失败:', error);
        }
    }

    // 初始化
    // 加载设备列表和活跃设备
    loadDevices();
    loadActiveDevices();
    loadAllSessions();
    

    
    // 初始化按钮状态
    toggleAutoScrollBtn.textContent = autoScroll ? '自动滚动: 开启' : '自动滚动: 关闭';
    if (autoScroll) {
        toggleAutoScrollBtn.classList.add('btn-active');
    } else {
        toggleAutoScrollBtn.classList.add('btn-inactive');
    }
    
    toggleDeduplicationBtn.textContent = `去重模式: ${useDeduplication ? '开启' : '关闭'}`;
    if (useDeduplication) {
        toggleDeduplicationBtn.classList.add('btn-active');
    } else {
        toggleDeduplicationBtn.classList.add('btn-inactive');
    }
    
    // 初始化状态指示器为实时日志模式
    updateStatusIndicator('realtime');
    
    initWebSocket();
    loadLogStats();
    loadDevices();
    loadActiveDevices();
    
    // 定期更新活跃设备
    setInterval(loadActiveDevices, 30000); // 每30秒更新一次
    
    // 切换去重模式
    function toggleDeduplication() {
        useDeduplication = !useDeduplication;
        toggleDeduplicationBtn.textContent = `去重模式: ${useDeduplication ? '开启' : '关闭'}`;
        
        // 更新按钮样式
        if (useDeduplication) {
            toggleDeduplicationBtn.classList.remove('btn-inactive');
            toggleDeduplicationBtn.classList.add('btn-active');
        } else {
            toggleDeduplicationBtn.classList.remove('btn-active');
            toggleDeduplicationBtn.classList.add('btn-inactive');
        }
        
        // 重新加载统计信息和历史日志（如果正在显示）
        loadLogStats();
        if (showingHistory) {
            currentPage = 1;
            loadHistoryLogs(1);
        }
        
        // 重新应用过滤器
        applyFilters();
    }

    // 加载日志统计
    async function loadLogStats() {
        try {
            const response = await fetch(`http://localhost:3333/api/logs/stats?deduplicated=${useDeduplication}`);
            if (response.ok) {
                const result = await response.json();
                updateStatsDisplay(result.data || result);
            }
        } catch (error) {
            console.error('加载日志统计失败:', error);
        }
    }
    
    // 更新统计显示
    function updateStatsDisplay(stats) {
        // 可以在页面上显示统计信息
        console.log('日志统计:', stats);
        
        // 如果有统计容器，更新显示
        const statsContainer = document.getElementById('stats-container');
        if (statsContainer && stats) {
            let statsHtml = '';
            
            if (useDeduplication && stats.unique_total !== undefined) {
                statsHtml = `
                    <div class="stats-item">
                        <span class="stats-label">去重日志数:</span>
                        <span class="stats-value">${stats.unique_total || 0}</span>
                    </div>
                    <div class="stats-item">
                        <span class="stats-label">总日志数:</span>
                        <span class="stats-value">${stats.total || 0}</span>
                    </div>
                `;
            } else {
                statsHtml = `
                    <div class="stats-item">
                        <span class="stats-label">总日志数:</span>
                        <span class="stats-value">${stats.total || 0}</span>
                    </div>
                `;
            }
            
            statsContainer.innerHTML = statsHtml;
        }
    }
    
    // 切换历史日志视图
    async function toggleHistoryView() {
        showingHistory = !showingHistory;
        
        if (showingHistory) {
            await loadHistoryLogs(1);
        } else {
            // 返回实时日志视图
            applyFilters();
        }
    }
    
    // 加载历史日志
    async function loadHistoryLogs(page = 1) {
        if (isLoadingHistory) return;
        
        isLoadingHistory = true;
        
        try {
            const params = new URLSearchParams({
                page: page,
                limit: 50,
                level: levelFilter.value !== 'all' ? levelFilter.value : '',
                module: moduleFilter.value !== 'all' ? moduleFilter.value : '',
                search: searchInput.value,
                deduplicated: useDeduplication
            });
            
            const response = await fetch(`http://localhost:3333/api/logs?${params}`);
            
            if (response.ok) {
                 const result = await response.json();
                 const data = result.data;
                 
                 if (page === 1) {
                     logs = data.logs;
                 } else {
                     logs = [...logs, ...data.logs];
                 }
                 
                 currentPage = data.pagination.page;
                 totalPages = data.pagination.totalPages;
                
                // 显示历史日志
                displayHistoryLogs();
                updatePaginationControls();
            }
        } catch (error) {
            console.error('加载历史日志失败:', error);
        } finally {
            isLoadingHistory = false;
        }
    }
    
    // 加载特定会话的日志
    async function loadSessionLogs(sessionId) {
        if (isLoadingHistory) return;
        
        isLoadingHistory = true;
        showingHistory = true;
        
        try {
            const params = new URLSearchParams({
                page: 1,
                limit: 1000, // 加载更多日志以显示完整会话
                sessionId: sessionId,
                deduplicated: false // 会话日志不使用去重
            });
            
            const response = await fetch(`http://localhost:3333/api/logs?${params}`);
            
            if (response.ok) {
                const result = await response.json();
                const data = result.data;
                
                // 显示会话日志，传递日志数据作为参数
                displaySessionLogs(sessionId, data.logs);
                
                // 隐藏分页控件（会话日志通常不需要分页）
                const paginationControls = document.querySelector('.pagination-controls');
                if (paginationControls) {
                    paginationControls.style.display = 'none';
                }
            } else {
                console.error('加载会话日志失败:', response.statusText);
                logContainer.innerHTML = '<div class="no-logs">加载会话日志失败</div>';
            }
        } catch (error) {
            console.error('加载会话日志失败:', error);
            logContainer.innerHTML = '<div class="no-logs">加载会话日志失败</div>';
        } finally {
            isLoadingHistory = false;
        }
    }
    
    // 显示会话日志
    function displaySessionLogs(sessionId, sessionLogs) {
        logContainer.innerHTML = '';
        
        // 更新状态指示器为历史日志模式
        updateStatusIndicator('history', '', sessionId);
        
        if (!sessionLogs || sessionLogs.length === 0) {
            logContainer.innerHTML = '<div class="no-logs">该会话暂无日志记录</div>';
            return;
        }
        
        // 添加会话标题
        const sessionHeader = document.createElement('div');
        sessionHeader.className = 'session-logs-header';
        sessionHeader.innerHTML = `
            <h3>会话 ${sessionId.substring(0, 8)} 的日志记录 (${sessionLogs.length} 条)</h3>
            <button onclick="backToRealtime()" class="back-btn">返回实时日志</button>
        `;
        logContainer.appendChild(sessionHeader);
        
        // 按时间排序日志（最新的在下面）
        const sortedLogs = sessionLogs.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
        
        sortedLogs.forEach(log => {
            const logEntry = document.createElement('div');
            logEntry.className = `log-entry ${log.level}`;
            
            const timestamp = formatTimestamp(log.timestamp);
            const message = log.message;
            
            logEntry.innerHTML = `
                <span class="log-timestamp">${timestamp}</span>
                <span class="log-level">${log.level}</span>
                <span class="log-module">${log.module}</span>
                <span class="log-message">${message}</span>
            `;
            
            logContainer.appendChild(logEntry);
        });
        
        // 滚动到底部显示最新日志
        logContainer.scrollTop = logContainer.scrollHeight;
    }
    
    // 返回实时日志
    window.backToRealtime = function() {
        showingHistory = false;
        document.querySelectorAll('.session-item').forEach(item => item.classList.remove('active'));
        
        // 更新状态指示器为实时日志模式
        updateStatusIndicator('realtime');
        
        // 显示分页控件
        const paginationControls = document.querySelector('.pagination-controls');
        if (paginationControls) {
            paginationControls.style.display = 'block';
        }
        
        // 在选择了特定设备时，重置会话过滤器为"全部会话"
        if (selectedDevice) {
            sessionFilter.value = 'all';
        }
        
        // 重新应用过滤器显示实时日志
        applyFilters();
    }

    // 显示历史日志
    function displayHistoryLogs() {
        // 使用表格视图来显示历史日志，这样可以支持折叠功能
        renderTableView(logs);
    }
    
    // 设置分页事件
    function setupPaginationEvents() {
        // 创建分页控件
        const paginationDiv = document.createElement('div');
        paginationDiv.id = 'pagination';
        paginationDiv.className = 'pagination';
        paginationDiv.style.display = 'none';
        
        const prevBtn = document.createElement('button');
        prevBtn.textContent = '上一页';
        prevBtn.addEventListener('click', () => {
            if (currentPage > 1) {
                loadHistoryLogs(currentPage - 1);
            }
        });
        
        const nextBtn = document.createElement('button');
        nextBtn.textContent = '下一页';
        nextBtn.addEventListener('click', () => {
            if (currentPage < totalPages) {
                loadHistoryLogs(currentPage + 1);
            }
        });
        
        const pageInfo = document.createElement('span');
        pageInfo.id = 'page-info';
        
        paginationDiv.appendChild(prevBtn);
        paginationDiv.appendChild(pageInfo);
        paginationDiv.appendChild(nextBtn);
        
        document.body.appendChild(paginationDiv);
    }
    
    // 更新分页控件
    function updatePaginationControls() {
        const pagination = document.getElementById('pagination');
        const pageInfo = document.getElementById('page-info');
        
        if (showingHistory && totalPages > 1) {
            pagination.style.display = 'block';
            pageInfo.textContent = `第 ${currentPage} 页，共 ${totalPages} 页`;
        } else {
            pagination.style.display = 'none';
        }
    }

    // 测试数据（开发时使用）
    function addTestLogs() {
        const levels = ['debug', 'info', 'warning', 'error', 'exception', 'emergency'];
        const modules = ['系统', '网络', '数据库', '用户界面', '安全'];
        const messages = [
            '应用程序已启动',
            '数据库连接成功',
            '用户已登录',
            '网络连接超时',
            '无法连接到服务器',
            '数据库查询失败',
            '内存使用率过高',
            '磁盘空间不足',
            '未授权访问尝试',
            '系统崩溃'
        ];

        // 添加一些单条日志
        for (let i = 0; i < 10; i++) {
            const level = levels[Math.floor(Math.random() * levels.length)];
            const module = modules[Math.floor(Math.random() * modules.length)];
            const message = messages[Math.floor(Math.random() * messages.length)];
            
            addLog({
                level,
                module,
                message,
                timestamp: new Date(Date.now() - Math.random() * 3600000).toISOString()
            });
        }

        // 添加一些重复日志（用于测试折叠功能）
        const repeatedLevel = 'error';
        const repeatedModule = '网络';
        const repeatedMessage = '无法连接到服务器';
        
        // 生成连续的重复日志，时间戳递增
        const baseTime = Date.now();
        for (let i = 0; i < 5; i++) {
            addLog({
                level: repeatedLevel,
                module: repeatedModule,
                message: repeatedMessage,
                timestamp: new Date(baseTime + i * 1000).toISOString() // 每秒递增
            });
        }
        
        // 再添加另一组重复日志
        const repeatedLevel2 = 'warning';
        const repeatedModule2 = '数据库';
        const repeatedMessage2 = '数据库查询失败';
        
        for (let i = 0; i < 3; i++) {
            addLog({
                level: repeatedLevel2,
                module: repeatedModule2,
                message: repeatedMessage2,
                timestamp: new Date(baseTime + 10000 + i * 1000).toISOString() // 10秒后开始
            });
        }
    }

    // 折叠所有会话功能
    function collapseAllSessions() {
        // 折叠所有会话容器
        const sessionContainers = logContainer.querySelectorAll('.session-container');
        sessionContainers.forEach(container => {
            const sessionLogs = container.querySelector('.session-logs');
            const sessionToggle = container.querySelector('.session-toggle');
            const sessionId = container.getAttribute('data-session-id');
            
            if (sessionLogs && sessionToggle) {
                // 设置为折叠状态
                sessionLogs.style.display = 'none';
                sessionToggle.textContent = '▶';
                
                // 更新状态记录
                if (sessionId) {
                    sessionCollapseStates.set(sessionId, true);
                }
            }
        });
        
        // 折叠表格视图中的日志组
        if (logGroups && logGroups.length > 0) {
            logGroups.forEach(group => {
                group.collapsed = true;
            });
            // 重新渲染表格以应用折叠状态
            const currentLogs = getCurrentFilteredLogs();
            renderTableView(currentLogs);
        }
        
        // 显示操作完成提示
        showToast('所有会话已折叠');
    }
    


    // 仅在开发环境中添加测试数据
    if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
        // 延迟1秒添加测试数据，模拟接收日志
        setTimeout(() => {
            if (!socket || socket.readyState !== WebSocket.OPEN) {
                console.log('WebSocket未连接，生成测试数据');
                addTestLogs();
            }
        }, 2000);
    }
    
    // 加载缓存的设备数据
    function loadCachedDevices() {
        const cached = DeviceCache.load();
        
        if (Object.keys(cached.devices).length > 0) {
            console.log(`从缓存加载了 ${Object.keys(cached.devices).length} 个设备`);
            
            // 恢复设备数据
            devices.clear();
            Object.entries(cached.devices).forEach(([id, device]) => {
                devices.set(id, device);
            });
            
            // 恢复活跃设备
            activeDevices.clear();
            cached.activeDevices.forEach(deviceId => {
                activeDevices.add(deviceId);
            });
            
            // 恢复设备会话
            deviceSessions.clear();
            Object.entries(cached.deviceSessions).forEach(([id, sessions]) => {
                deviceSessions.set(id, sessions);
            });
            
            // 更新界面
            updateDeviceList();
            updateActiveDevicesCount();
            
            return true;
        }
        
        return false;
    }
    
    // 启动初始化
    initializePage();
});